package zsc.liangyi.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import zsc.liangyi.blog.model.domain.User;
import zsc.liangyi.blog.service.UserService;
import zsc.liangyi.blog.service.impl.UserServiceImpl;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class UserUtils {
    public static UserUtils userUtils;
    @Autowired
    private  UserService userService;
    @PostConstruct
    public void init() {
        userUtils = this;
    }

    //根据上下文获取当前登录用户
    public static User getUser(){
//        获取应用上下文
        SecurityContextImpl context= (SecurityContextImpl) SecurityContextHolder.getContext();
        log.info("上下文："+context);
        //获取用户信息
        Authentication authentication=context.getAuthentication();
        //密码
        CredentialsContainer container=null;
        UserDetails principal=(UserDetails)authentication.getPrincipal();
        log.info("登录用户名："+principal.getUsername());
        //存入User实体类
        User user=userUtils.userService.getByUserName(principal.getUsername());
        log.info("用户信息："+user);
        return user;
    }
}
